package new

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/spf13/cobra"

	"gitcode.com/goinit/goinit/internal/pkg/filex"
	"gitcode.com/goinit/goinit/internal/pkg/mod"
	"gitcode.com/goinit/goinit/internal/tpl"
	"gitcode.com/goinit/goinit/internal/tpl/handle"
	"gitcode.com/goinit/goinit/internal/tpl/middleware"
	"gitcode.com/goinit/goinit/internal/tpl/migrate"
	"gitcode.com/goinit/goinit/internal/tpl/repository"
	"gitcode.com/goinit/goinit/internal/tpl/server"
	"gitcode.com/goinit/goinit/internal/tpl/service"
)

var cmdByService = &cobra.Command{
	Use:     "module",
	Short:   "Create a new module framework",
	Example: "goinit new module user",
	Run: func(cmd *cobra.Command, args []string) {
		modName, err := mod.Name()
		if modName == "" || err != nil {
			fmt.Println("go.mod 文件不存在")
			return
		}

		if len(args) < 1 {
			cmd.Help()
			return
		}
		serverName := args[0]
		if serverName == "" {
			cmd.Help()
			return
		}

		path, _ := os.Getwd()
		touchServiceFiles(path, serverName, modName)
	},
}

func touchServiceFiles(path, serverName, modName string) {
	value := map[string]string{
		"ServerName":     serverName,
		"ModName":        modName,
		"ModelName":      "user",
		"HandlerName":    "user",
		"ServiceName":    "user",
		"RepositoryName": "user",
	}

	files := map[string]string{
		filepath.Join(path, "cmd", serverName, "main.go"):                                 string(tpl.Main),
		filepath.Join(path, "internal", "app", serverName, "server", "init.go"):           string(server.Init),
		filepath.Join(path, "internal", "app", serverName, "server", "http.go"):           string(server.Server),
		filepath.Join(path, "internal", "app", serverName, "middleware", "logger.go"):     string(middleware.Logger),
		filepath.Join(path, "internal", "app", serverName, "migrate", "migrate.go"):       string(migrate.Migrate),
		filepath.Join(path, "internal", "app", serverName, "handler", "handler.go"):       string(handle.Handle),
		filepath.Join(path, "internal", "app", serverName, "service", "service.go"):       string(service.Service),
		filepath.Join(path, "internal", "app", serverName, "repository", "repository.go"): string(repository.Repository),
	}

	for f, content := range files {
		filex.Create(f, content, value)
	}
}
